package com.atguigu.case3;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CuratorLockTest {
    public static void main(String[] args) {
        //创建分布式锁1
        InterProcessMutex lock1 = new InterProcessMutex(getcuratorFramework(), "/lock");
        //创建分布式锁2
        InterProcessMutex lock2 = new InterProcessMutex(getcuratorFramework(), "/lock");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    lock1.acquire();//获取到锁
                    System.out.println("线程1获取到锁");
                    lock1.acquire();//获取到锁
                    System.out.println("线程1再次获取到锁");
                    Thread.sleep(5000);
                    lock1.release();
                    System.out.println("线程1释放锁");
                    lock1.release();
                    System.out.println("线程1再次释放锁");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    lock2.acquire();//获取到锁
                    System.out.println("线程2获取到锁");
                    lock2.acquire();//获取到锁
                    System.out.println("线程2再次获取到锁");
                    Thread.sleep(5000);
                    lock2.release();
                    System.out.println("线程2释放锁");
                    lock2.release();
                    System.out.println("线程2再次释放锁");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private static CuratorFramework getcuratorFramework(){
        CuratorFramework client = CuratorFrameworkFactory.builder().connectString("192.168.80.130:2181,192.168.80.131:2181,192.168.80.132:2181")
                .connectionTimeoutMs(2000)
                .sessionTimeoutMs(2000)
                .retryPolicy(new ExponentialBackoffRetry(3000, 3))
                .build();
        //启动客户端
        client.start();
        System.out.println("zookeeper启动成功");
        return client;
    }
}
